import os
import logging
from logging.handlers import TimedRotatingFileHandler

def getLogger():
    datefmt = '%Y-%m-%d %H:%M:%S'
    format = '%(asctime)s:%(msecs)03d - %(threadName)s[%(thread)d] %(filename)s %(funcName)s [line:%(lineno)s] - %(levelname)s: %(message)s'

    name = "AppLog"
    logger = logging.getLogger(name)
    logger.setLevel(logging.INFO)

    # 文件处理器（按天切割日志）
    log_dir = "../logs"
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)
    log_file = os.path.join(log_dir, name + ".log")
    file_handler = TimedRotatingFileHandler(
        log_file,
        when = "midnight",        # 每天午夜轮转
        interval = 1,
        backupCount = 7,          # 保留 7 天日志
        encoding = 'utf-8'
    )
    file_handler.suffix = "%Y-%m-%d.log"
    file_handler.setFormatter(logging.Formatter(format))

    # 控制台处理器
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.INFO)

    logging.basicConfig(
        level = logging.INFO,
        format = format,
        datefmt = datefmt,
        handlers = [ file_handler, console_handler ]
    )

    return logger
